package tools;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class CheckFileTools {
	/**
	 * @param filePath  文件路径
	 * @return 输出文件路径下文件个数
	 */
	public static int getFileNum(String filePath)
	{
		try
		{
			Configuration conf = new Configuration();
			FileSystem fs= FileSystem.get(conf);
			FileStatus[] fileStatus;
			fileStatus = fs.listStatus(new Path(filePath));
			return fileStatus.length;
		}
		catch (IOException e)
		{
			return 0;
		}
	}

	public static boolean checkSuccess(String filePath){
		try
		{
			Configuration conf = new Configuration();
			FileSystem fs= FileSystem.get(conf);
			FileStatus[] fileStatus;
			fileStatus = fs.listStatus(new Path(filePath));
			for(FileStatus fileStatu : fileStatus){
				String fileName=fileStatu.getPath().getName();
				System.out.println("fileName:"+fileName);
				if(fileName.contains("SUCCESS")){
					return true;
				}
			}
			return false;
		}
		catch (IOException e)
		{
			return false;
		}
	}

	/**
	 * @param path   检测路径
	 * @param maxNum   最大检测次数
	 * @param sleepMillis  每次检测时间间隔
	 * @param pathMinNum 检测路径中文件最小合格个数
	 * @return
	 */
	public static int myJobWait(String path,int maxNum,long sleepMillis,int pathMinNum){
		int num=0;
		//while (getFileNum(path)<pathMinNum )
		while(!checkSuccess(path))
		{
			System.out.println("上游数据源目录文件未生成！！！");
			//
			num=num+1;
			if(num==maxNum){
				break;
			}
			try
			{
				Thread.sleep(sleepMillis);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		return 0;
	}
}
